<template>
  <div class="create-team-container">
    <!-- 顶部导航 -->
    <header class="header">
      <button class="back-btn" @click="goBack">
        <span class="back-icon">‹</span>
        返回
      </button>
    </header>

    <!-- 主要内容 -->
    <main class="main-content">
      <!-- 页面标题 -->
      <h1 class="page-title">{{ isEditMode ? '管理队伍成员' : '组建队伍' }}</h1>

      <!-- Tab切换 -->
      <div class="tab-container">
        <button class="tab-btn" :class="{ active: activeTab === 'intelligent' }" @click="switchTab('intelligent')">
          智能推荐
        </button>
        <button class="tab-btn" :class="{ active: activeTab === 'precise' }" @click="switchTab('precise')">
          精准检索
        </button>
      </div>

      <!-- 队伍类型选择 -->
      <div class="team-type-section">
        <span class="section-label">{{ isEditMode ? '队伍学院' : '队伍类型' }}</span>
        <div class="select-container">
          <select v-model="selectedTeamType" class="team-type-select">
            <option value="">请选择学院</option>
            <option value="计算机科学与技术学院">计算机科学与技术学院</option>
            <option value="软件学院">软件学院</option>
            <option value="信息工程学院">信息工程学院</option>
            <option value="数据科学学院">数据科学学院</option>
            <option value="人工智能学院">人工智能学院</option>
            <option value="网络空间安全学院">网络空间安全学院</option>
          </select>
          <button 
            class="recommend-btn" 
            @click="getRecommendations"
            :disabled="!selectedTeamType || loading"
          >
            {{ loading ? '推荐中...' : '智能推荐' }}
          </button>
        </div>
      </div>
      <!-- 搜索功能（精准检索模式下显示） -->
      <div v-if="activeTab === 'precise'" class="search-section">
        <div class="search-container">
          <input 
            v-model="searchKeyword" 
            type="text" 
            placeholder="搜索学生姓名、学号..."
            class="search-input"
            @input="handleSearch"
            @keyup.enter="handleSearch"
            :disabled="!selectedTeamType"
          />
          <button 
            class="search-btn" 
            @click="handleSearch"
            :disabled="!selectedTeamType"
          >🔍</button>
        </div>
        
        <!-- 选择学院提示 -->
        <div v-if="!selectedTeamType" class="college-tip">
          <div class="tip-icon">💡</div>
          <div class="tip-content">
            <div class="tip-text">请先选择学院，然后输入学生姓名或学号进行搜索</div>
          </div>
        </div>
        
        <!-- 搜索提示 -->
        <div v-else-if="selectedTeamType && !searchKeyword.trim() && searchedStudents.length === 0" class="search-tip">
          <div class="tip-icon">🔍</div>
          <div class="tip-content">
            <div class="tip-text">在上方搜索框中输入学生姓名或学号开始搜索</div>
          </div>
        </div>
      </div>

      <!-- 已选学生数量显示 -->
      <div v-if="activeTab === 'intelligent' || searchKeyword.trim()" class="selected-info">
        <span class="selected-count">已选择 {{ selectedStudents.length }}/30 名学生</span>
        <button v-if="selectedStudents.length > 0" class="clear-btn" @click="clearSelected">
          清空选择
        </button>
      </div>

      <!-- 学生列表 -->
      <div v-if="activeTab === 'intelligent' || searchKeyword.trim()" class="student-list">
        <div class="list-header">
          <div class="header-item">姓名</div>
          <div class="header-item">学号</div>
          <div class="header-item">学院</div>
          <div class="header-item">操作</div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-text">正在加载学生信息...</div>
        </div>

        <!-- 学生列表项 -->
        <div v-else class="student-items">
          <div v-for="student in currentStudents" :key="student.id" class="student-item"
            :class="{ selected: isSelected(student.id) }">
            <div class="student-info">
              <span class="student-name">{{ student.realName }}</span>
            </div>
            <div class="student-info">
              <span class="student-number">{{ student.studentId }}</span>
            </div>
            <div class="student-info">
              <span class="student-college">{{ student.college }}</span>
            </div>
            <div class="student-action">
              <button class="action-btn" :class="{ 'remove-btn': isSelected(student.id) }"
                @click="toggleStudent(student)" :disabled="!isSelected(student.id) && selectedStudents.length >= 30">
                {{ isSelected(student.id) ? '−' : '+' }}
              </button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && currentStudents.length === 0" class="empty-state">
          <div class="empty-icon">👥</div>
          <div class="empty-text">
            {{ activeTab === 'intelligent' ? '暂无推荐学生' : '暂无符合条件的学生' }}
          </div>
          <div class="empty-hint">
            {{ activeTab === 'intelligent' ? '请选择学院后点击智能推荐' : '请尝试调整搜索条件' }}
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div v-if="activeTab === 'intelligent' || searchKeyword.trim()" class="bottom-actions">
        <button class="next-btn" :disabled="selectedStudents.length === 0" @click="showCandidates">
          查看候选人 ({{ selectedStudents.length }})
        </button>
      </div>
    </main>

        <!-- 候选人查看弹窗 -->
    <div v-if="showCandidatesModal" class="candidates-overlay" @click="closeCandidatesModal">
      <div class="candidates-popup" @click.stop>
        <!-- 弹窗头部 -->
        <div class="popup-header">
          <h2 class="popup-title">候选人</h2>
          <button class="popup-close" @click="closeCandidatesModal">×</button>
        </div>
        
        <!-- 候选人列表 -->
        <div class="popup-body">
          <!-- 角色加载状态 -->
          <div v-if="rolesLoading" class="roles-loading">
            <div class="loading-icon">⏳</div>
            <div class="loading-text">正在加载角色选项...</div>
          </div>
          
          <div v-else class="candidates-scroll">
            <div 
              v-for="student in selectedStudents" 
              :key="student.id"
              class="candidate-item"
            >
              <!-- 移除按钮 -->
              <button 
                class="candidate-remove-btn"
                @click="removeCandidateFromModal(student.id)"
                title="移除候选人"
              >
                ×
              </button>
              
              <!-- 学生头像 -->
              <div class="student-avatar">
                <div class="avatar-circle">
                  {{ student.realName.charAt(0) }}
                </div>
              </div>
              
              <!-- 学生信息 -->
              <div class="student-details">
                <div class="student-name">{{ student.realName }}</div>
                <div class="student-id">{{ student.studentId }}</div>
                <div class="student-college">{{ student.college }}</div>
              </div>
              
              <!-- 身份选择 -->
              <div class="role-selector">
                <select 
                  v-model="student.memberRole" 
                  class="role-dropdown"
                  @change="updateStudentRole(student.id, student.memberRole)"
                  :disabled="rolesLoading"
                >
                  <option v-if="rolesLoading" value="">加载中...</option>
                  <option 
                    v-else
                    v-for="role in memberRoles" 
                    :key="role.id" 
                    :value="role.roleName || role.role_name"
                  >
                    {{ role.roleName || role.role_name }}
                  </option>
                </select>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 弹窗底部 -->
        <div class="popup-footer">
          <button class="btn-secondary" @click="closeCandidatesModal" :disabled="loading">
            返回选择
          </button>
          <button 
            class="btn-primary" 
            @click="goToTeamInfo"
            :disabled="selectedStudents.length === 0 || loading || rolesLoading"
          >
            {{ loading ? (isEditMode ? '更新中...' : '创建中...') : (isEditMode ? '确定更新 ✨' : '确定组建 ✨') }}
          </button>
        </div>
      </div>
    </div>

    <!-- 创建成功提示弹窗 -->
    <div v-if="showSuccessModal" class="success-overlay" @click="handleSuccessConfirm">
      <div class="success-popup" @click.stop>
        <!-- 弹窗头部 -->
        <div class="success-header">
          <div class="success-icon">🎉</div>
          <h2 class="success-title">创建成功！</h2>
        </div>
        
        <!-- 弹窗内容 -->
        <div class="success-body">
          <div class="team-success-info">
            <div class="success-item">
              <span class="success-label">队伍名称：</span>
              <span class="success-value">{{ createdTeamInfo.teamName }}</span>
            </div>
            <div class="success-item">
              <span class="success-label">队伍编号：</span>
              <span class="success-value">{{ createdTeamInfo.teamCode }}</span>
            </div>
            <div class="success-item">
              <span class="success-label">队伍成员：</span>
              <span class="success-value">{{ createdTeamInfo.memberCount }} 人</span>
            </div>
          </div>
          <div class="success-message">
            <p>🌟 恭喜您成功创建了一个新队伍！</p>
            <p>💡 您可以在队伍详情页面继续完善队伍信息</p>
          </div>
        </div>
        
        <!-- 弹窗底部 -->
        <div class="success-footer">
          <button class="success-btn" @click="handleSuccessConfirm">
            查看队伍详情 🚀
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getRecommendStudentsService, searchStudentsService } from '@/api/student.js'
import { createTeamService, getMemberRolesService, getTeamEditInfoService, updateTeamMembersService } from '@/api/team.js'
import { useTeacherStore } from '@/stores/teacher.js'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()

// 响应式数据
const activeTab = ref('intelligent') // 当前激活的tab
const selectedTeamType = ref('') // 选择的队伍类型（学院）
const searchKeyword = ref('') // 搜索关键词
const loading = ref(false) // 加载状态
const selectedStudents = ref([]) // 已选择的学生
const showCandidatesModal = ref(false) // 候选人弹窗显示状态
const memberRoles = ref([]) // 队员角色选项
const rolesLoading = ref(false) // 角色加载状态
const showSuccessModal = ref(false) // 成功提示弹窗显示状态
const createdTeamInfo = ref({}) // 创建成功的队伍信息
const isEditMode = ref(false) // 是否为编辑模式
const currentTeamData = ref({}) // 当前编辑的队伍数据

// 学生数据
const recommendedStudents = ref([]) // 智能推荐的学生列表
const searchedStudents = ref([]) // 精准搜索的学生列表

// 计算属性：当前显示的学生列表
const currentStudents = computed(() => {
  if (activeTab.value === 'intelligent') {
    return recommendedStudents.value
  } else {
    return searchedStudents.value
  }
})

// 页面挂载时的初始化
onMounted(async () => {
  console.log('create-team页面挂载 - route:', route)
  console.log('路由参数:', route.params)
  console.log('路由查询:', route.query)
  
  // 检测是否为编辑模式
  if (route.params.teamId && route.query.mode === 'edit') {
    console.log('进入编辑模式 - teamId:', route.params.teamId)
    isEditMode.value = true
    await loadTeamDataForEdit(route.params.teamId)
  } else {
    console.log('进入新建模式')
  }
})

// 加载队伍编辑数据
const loadTeamDataForEdit = async (teamId) => {
  loading.value = true
  try {
    console.log('加载队伍编辑数据:', teamId)
    const result = await getTeamEditInfoService(teamId)
    
    if (result.code === 200) {
      const teamData = result.data
      currentTeamData.value = {
        ...teamData,
        teamId: teamData.teamId || teamId // 确保teamId被保存
      }
      
      // 设置队伍类型（学院）
      selectedTeamType.value = teamData.teamType || ''
      
      // 加载角色数据
      await loadMemberRoles()
      
      // 设置已选择的学生
      if (teamData.members && teamData.members.length > 0) {
        selectedStudents.value = teamData.members.map(member => ({
          id: member.studentId,
          realName: member.realName,
          studentId: member.studentNumber || member.studentId,
          college: member.college,
          memberRole: member.memberRole
        }))
      }
      
      // 切换到智能推荐模式显示成员
      activeTab.value = 'intelligent'
      
      console.log('队伍编辑数据加载成功:', teamData)
      console.log('已选择的学生:', selectedStudents.value)
    } else {
      console.error('加载队伍编辑数据失败:', result.msg)
      alert(result.msg || '加载队伍数据失败')
      router.go(-1) // 加载失败则返回上一页
    }
  } catch (error) {
    console.error('加载队伍编辑数据异常:', error)
    alert('加载队伍数据失败，请稍后重试')
    router.go(-1)
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 切换tab
const switchTab = (tab) => {
  activeTab.value = tab
  if (tab === 'intelligent') {
    searchKeyword.value = ''
    searchedStudents.value = [] // 清空搜索结果
  } else {
    recommendedStudents.value = [] // 清空推荐结果
  }
}

// 获取智能推荐
const getRecommendations = async () => {
  if (!selectedTeamType.value) {
    alert('请先选择学院')
    return
  }

  loading.value = true
  try {
    console.log(`获取${selectedTeamType.value}的智能推荐`)
    const result = await getRecommendStudentsService(selectedTeamType.value)
    
    if (result.code === 200) {
      recommendedStudents.value = result.data || []
      console.log('智能推荐成功:', result.data)
    } else {
      console.error('智能推荐失败:', result.msg)
      alert(result.msg || '智能推荐失败')
      recommendedStudents.value = []
    }
  } catch (error) {
    console.error('获取推荐失败:', error)
    alert('获取推荐失败，请稍后重试')
    recommendedStudents.value = []
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = async () => {
  if (!selectedTeamType.value) {
    // 不显示alert，依靠界面提示
    return
  }
  
  // 如果没有搜索关键词，清空搜索结果
  if (!searchKeyword.value.trim()) {
    searchedStudents.value = []
    return
  }

  loading.value = true
  try {
    console.log(`搜索学生 - 学院: ${selectedTeamType.value}, 关键词: ${searchKeyword.value}`)
    const result = await searchStudentsService(selectedTeamType.value, searchKeyword.value.trim())
    
    if (result.code === 200) {
      searchedStudents.value = result.data || []
      console.log('搜索成功:', result.data)
    } else {
      console.error('搜索失败:', result.msg)
      alert(result.msg || '搜索失败')
      searchedStudents.value = []
    }
  } catch (error) {
    console.error('搜索学生失败:', error)
    alert('搜索失败，请稍后重试')
    searchedStudents.value = []
  } finally {
    loading.value = false
  }
}

// 检查学生是否已选择
const isSelected = (studentId) => {
  return selectedStudents.value.some(student => student.id === studentId)
}

// 切换学生选择状态
const toggleStudent = (student) => {
  const index = selectedStudents.value.findIndex(s => s.id === student.id)

  if (index > -1) {
    // 取消选择
    selectedStudents.value.splice(index, 1)
  } else {
    // 添加选择（最多30个）
    if (selectedStudents.value.length < 30) {
      // 添加默认身份（先设为空，在弹窗打开时会设置）
      const studentWithRole = { ...student, memberRole: '' }
      selectedStudents.value.push(studentWithRole)
    }
  }
}

// 清空选择
const clearSelected = () => {
  selectedStudents.value = []
}

// 显示候选人弹窗
const showCandidates = async () => {
  if (selectedStudents.value.length === 0) {
    return
  }
  
  // 加载角色数据
  await loadMemberRoles()
  
  showCandidatesModal.value = true
}

// 加载队员角色
const loadMemberRoles = async () => {
  if (memberRoles.value.length > 0) {
    // 如果已经加载过，直接返回
    return
  }
  
  rolesLoading.value = true
  try {
    console.log('加载队员角色列表...')
    const result = await getMemberRolesService()
    
    if (result.code === 200) {
      memberRoles.value = result.data || []
      console.log('角色列表加载成功:', result.data)
      
      // 为没有角色的学生设置默认角色（取第一个角色，通常是"队员"）
      // 支持 roleName 和 role_name 两种字段名
      const defaultRole = memberRoles.value.find(role => 
        (role.roleName === '队员' || role.role_name === '队员')
      ) || memberRoles.value[0]
      
      if (defaultRole) {
        const defaultRoleName = defaultRole.roleName || defaultRole.role_name
        selectedStudents.value.forEach(student => {
          if (!student.memberRole) {
            student.memberRole = defaultRoleName
          }
        })
      }
    } else {
      console.error('加载角色列表失败:', result.msg)
      alert(result.msg || '加载角色列表失败')
    }
  } catch (error) {
    console.error('加载角色列表异常:', error)
    alert('加载角色列表失败，请稍后重试')
  } finally {
    rolesLoading.value = false
  }
}

// 关闭候选人弹窗
const closeCandidatesModal = () => {
  showCandidatesModal.value = false
}

// 更新学生身份
const updateStudentRole = (studentId, newRole) => {
  const student = selectedStudents.value.find(s => s.id === studentId)
  if (student) {
    student.memberRole = newRole
  }
  
  // 确保只有一个队长
  if (newRole === '队长') {
    // 找到默认角色（通常是"队员"）
    const defaultRole = memberRoles.value.find(role => 
      (role.roleName === '队员' || role.role_name === '队员')
    ) || memberRoles.value[0]
    const defaultRoleName = defaultRole ? (defaultRole.roleName || defaultRole.role_name) : '队员'
    
    selectedStudents.value.forEach(s => {
      if (s.id !== studentId && s.memberRole === '队长') {
        s.memberRole = defaultRoleName
      }
    })
  }
}

// 从候选人弹窗中移除学生
const removeCandidateFromModal = (studentId) => {
  const index = selectedStudents.value.findIndex(s => s.id === studentId)
  if (index > -1) {
    selectedStudents.value.splice(index, 1)
  }
}

// 前往团队信息页面
const goToTeamInfo = async () => {
  if (selectedStudents.value.length === 0) {
    return
  }

  // 验证是否有队长
  const hasLeader = selectedStudents.value.some(s => s.memberRole === '队长')
  if (!hasLeader) {
    alert('请至少指定一名队长')
    return
  }

  // 验证所有学生都已分配角色
  const hasEmptyRole = selectedStudents.value.some(s => !s.memberRole || s.memberRole.trim() === '')
  if (hasEmptyRole) {
    alert('请为所有学生分配角色')
    return
  }

  // 显示加载状态
  loading.value = true

  try {
    if (isEditMode.value) {
      // 编辑模式：更新队伍成员
      await updateTeamMembers()
    } else {
      // 新建模式：创建队伍
      await createNewTeam()
    }
  } catch (error) {
    console.error('操作失败:', error)
    alert(isEditMode.value ? '更新队伍失败，请稍后重试' : '创建队伍失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 更新队伍成员
const updateTeamMembers = async () => {
  console.log('开始更新队伍成员 - route:', route)
  console.log('route.params:', route.params)
  console.log('currentTeamData:', currentTeamData.value)
  
  // 安全获取teamId
  const teamId = route.params?.teamId || currentTeamData.value?.teamId
  
  if (!teamId) {
    console.error('无法获取队伍ID')
    throw new Error('无法获取队伍ID，请重新进入编辑页面')
  }

  const updateData = {
    teamType: selectedTeamType.value,
    members: selectedStudents.value.map(student => ({
      studentId: student.id,
      memberRole: student.memberRole
    }))
  }

  console.log('更新队伍成员数据 - teamId:', teamId, 'updateData:', updateData)

  const result = await updateTeamMembersService(teamId, updateData)

  if (result.code === 200) {
    // console.log('队伍成员更新成功！')
    ElMessage.success('队伍成员更新成功！')
    
    // 关闭弹窗
    closeCandidatesModal()
    
    // 显示成功提示并返回个人中心
    ElMessage.success('队伍成员更新成功！')
    router.push({
      name: 'TeamDetail',
      params: { 
        teamId: teamId,
        teamData: encodeURIComponent(JSON.stringify(currentTeamData.value))
      }
    })
  } else {
    console.error('更新队伍成员失败:', result.msg)
    throw new Error(result.msg || '更新队伍成员失败，请稍后重试')
  }
}

// 创建新队伍
const createNewTeam = async () => {
  // 构造队伍创建数据（按照后端TeamCreateVO格式）
  const teamData = {
    teamType: selectedTeamType.value,
    members: selectedStudents.value.map(student => ({
      studentId: student.id,
      memberRole: student.memberRole
    }))
  }

  console.log('创建队伍数据:', teamData)

  // 调用创建队伍API
  const result = await createTeamService(teamData)

  if (result.code === 200) {
    // 创建成功，记录生成的队伍信息
    console.log('队伍创建成功！')
    console.log('队伍ID:', result.data.teamId)
    console.log('队伍编号:', result.data.teamCode)
    console.log('生成的队伍名称:', result.data.teamName)
    
    // 关闭弹窗
    closeCandidatesModal()
    
    // 构造跳转数据
    const teamDetailData = {
      teamInfo: {
        id: result.data.teamId,
        teamName: result.data.teamName || '新建队伍', // 使用后端生成的有趣队伍名称
        teamCode: result.data.teamCode,
        teamType: teamData.teamType,
        instructorId: getCurrentUserId(),
        teamIntro: '',
        currentCompetition: '',
        awardInfo: '',
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      },
      selectedStudents: selectedStudents.value,
      // instructorInfo 会在 team-detail.vue 中从 TeacherStore 获取
      experts: []
    }

    // 保存创建成功的队伍信息
    createdTeamInfo.value = {
      teamId: result.data.teamId,
      teamName: result.data.teamName,
      teamCode: result.data.teamCode,
      memberCount: selectedStudents.value.length,
      teamDetailData: teamDetailData
    }

    // 显示成功提示弹窗
    showSuccessModal.value = true
  } else {
    console.error('创建队伍失败:', result.msg)
    throw new Error(result.msg || '创建队伍失败，请稍后重试')
  }
}

// 获取当前用户ID
const getCurrentUserId = () => {
  // 从用户状态管理获取当前登录用户的ID
  const teacherStore = useTeacherStore()
  return teacherStore.teacherInfo?.id || null
}

// 处理成功提示确认
const handleSuccessConfirm = () => {
  showSuccessModal.value = false
  
  // 跳转到队伍详情页面
  router.push({
    name: 'TeamDetail',
    params: { 
      teamId: createdTeamInfo.value.teamId,
      teamData: encodeURIComponent(JSON.stringify(createdTeamInfo.value.teamDetailData))
    }
  })
}
</script>

<style scoped lang="scss">
@import '@/assets/css/create-team.css';
</style>